<template>
  <!-- 添加分类的对话框 -->
  <el-dialog
    title="添加分类"
    v-model="addDialogVisible"
    width="50%"
    @close="addDialogClose"
  >
    <!-- 内容主体区域 -->
    <!-- 表单中model和rules名称不可以相同 -->
    <el-form
      ref="addCateFormRef"
      :model="addCateForm"
      :rules="addCateFormRules"
      label-width="80px"
    >
      <el-form-item label="分类名称" prop="cateName">
        <el-input v-model="addCateForm.cateName"></el-input>
      </el-form-item>
      <el-form-item label="父级分类">
        <el-cascader
          style="width:100%"
          v-model="selectedKeys"
          :options="cateKeyNames"
          :props="{
            checkStrictly: true,
            expandTrigger: 'hover',
            value: 'id',
            label: 'cateName',
            children: 'children'
          }"
          @change="parentCateChange"
          clearable
        >
        </el-cascader>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogClose">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { addCategory } from "network/category.js";
export default {
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false
    },
    // 级联选择器绑定的数据源
    cateKeyNames: {
      type: Array,
      default: []
    },
    // 表单的验证规则对象
    addCateFormRules: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      addCateForm: {
        // 要添加的分类的名称
        cateName: "",
        // 父级分类的id
        parentId: "",
        // 父级分类的id,默认0:一级分类,1:二级分类,2:三级分类
        level: 0
      },
      // 级联选择器选定的数据
      selectedKeys: []
    };
  },
  emits: ["addDialogClose"],
  methods: {
    //监听添加用户对话框的关闭事件
    addDialogClose() {
      this.$emit("addDialogClose");
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.parentId = "";
      this.addCateForm.level = 0;
    },
    //选择项发生变化,触发函数
    parentCateChange() {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.addCateForm.level = this.selectedKeys.length;
        this.addCateForm.parentId = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
      } else {
        this.addCateForm.level = 0;
        this.addCateForm.parentId = "";
      }
    },
    async addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        // console.log(valid);//校验成功true,失败false
        if (!valid) return;
        //发起网络请求
        const res = await addCategory(this.addCateForm);
        if (res.status !== 201)
          return this.$message.error({ showClose: true, message: res.msg });
        this.$message.success({ showClose: true, message: res.msg });
        this.$emit("addDialogClose", true);
      });
    }
  }
};
</script>

<style lang="less" scoped></style>
